<template>
  <div @viewappear="viewappear" style="overflow: hidden;">
    <navbar theme="light" :leftBack="step !==  2" @leftItemClick="navbarLeftItemClick" :leftItemText="leftItemText" :title="params.weixinBindOpenId ? '绑定新账号' : '用户注册'"></navbar>
    <div :class="['login-form', 'panel', step == 1 && 'panel-show']">
      <div class="form-row">
        <text class="form-row-icon icon">&#xe71f;</text>
        <xinput placeholder="输入邀请码或者推荐人手机号" v-bind:key="inviteCode" type="number" maxLength="20" :value.sync="params.inviteCode" class="form-row-control"></xinput>
      </div>
      <div class="form-row">
        <text class="form-row-icon icon">&#xe704;</text>
        <xinput placeholder="请输入您的手机号" :value.sync="params.phone" v-bind:key="phone" type="tel"
                maxLength="11" class="form-row-control"></xinput>
      </div>
      <div class="form-bottom">
        <text :class="['btn-primary','btn','btn-large', step1ValidateOk || 'btn-disabled', 'login-btn', 'activeable']"
              @click="checkStep1()">下一步</text>
      </div>
    </div>
    <div :class="['login-form', 'panel', step == 2 && 'panel-show']">
      <div class="form-row">
        <text class="form-row-icon icon">&#xe769;</text>
        <xinput placeholder="输入手机验证码" type="number" v-bind:key="verifyCode" maxLength="6" :value.sync="params.verifyCode"
                class="form-row-control"></xinput>
        <text class="form-row-btn activeable" @click="sendMsg">{{cooldown ? '剩余' + cooldown + 's' : '获取验证码'}}</text>
      </div>
      <div class="form-row">
        <text class="form-row-icon icon text-warning" v-if="hidePwd" @click="toggleHidePwd">&#xe61e;</text>
        <text class="form-row-icon icon text-warning" v-if="!hidePwd" @click="toggleHidePwd">&#xe73c;</text>
        <xinput placeholder="请输入密码（6-16）位" :value.sync="params.password" v-bind:key="password" maxLength="16"
                :type="hidePwd ? 'password' : 'text'" class="form-row-control"></xinput>
      </div>
      <div class="form-bottom">
        <text :class="['btn-primary','btn','btn-large', (step1ValidateOk && step2ValidateOk) || 'btn-disabled', 'login-btn']"
              @click="register">同意协议并注册</text>
      </div>
      <div class="form-row-text">
        <div class="agreement">
          <text class="agreement-txt">已阅读并同意</text>
          <text class="agreement-txt agreement-txt-link activeable" @click="showXy">《辣小客用户协议》</text>
          <text class="agreement-txt">协议</text>

        </div>
      </div>
    </div>
    <div :class="['register-success', 'panel', step == 3 && 'panel-show']">
      <div class="register-success-top">
        <image class="success-pic" :src="successPic" resize="cover"></image>
        <text class="success-text">恭喜您，注册成功</text>
      </div>
      <div style="align-items: center">
        <text class="btn-primary btn btn-large" style="width: 700" @click="back">现在去登录</text>
      </div>
    </div>
  </div>
</template>
<script>
require('./include/page-xdom')
let api = require('./include/api')
let broadcastChannelKeys = require('./include/broadcast-channel-keys')
let BroadcastChannel = require('./include/broadcast-channel')
let registerBroadcastChannel = new BroadcastChannel(broadcastChannelKeys.REGISTER)
let urlPath = require('./include/url-path')
let modal = weex.requireModule('modal')
let navigator = require('./include/xnavigator')
let queryParser = require('./include/queryparser')
let clipboard = weex.requireModule('clipboard')
let config = require('./include/app-config')
module.exports = {
  mixins: [],
  components: {
    navbar: require('./components/navbar.vue'),
    xinput: require('./components/input.vue')
  },
  data () {
    return {
      logoSrc: urlPath.assets('images/logo_la.png?v=1'),
      hidePwd: true,
      validateOk: false,
      step1ValidateOk: false,
      cooldown: 0,
      registerDoing: false,
      registered: false,
      iosShow: false,
      leftItemText: null,
      step: 1,
      successPic: urlPath.assets('images/success.png?v=3'),
      weixinBound: false,
      params: {
        phone: '',
        inviteCode: '',
        verifyCode: '',
        password: '',
        weixinBindOpenId: ''
      }
    }
  },
  beforeDestroy () {
    registerBroadcastChannel.postMessage({
      registered: this.registered,
      phone: this.params.phone,
      password: this.params.password,
      weixinBound: this.weixinBound
    })
  },
  created () {
    config.bindConfig(this)
    let queryParams = queryParser(this.$getConfig().bundleUrl)
    this.params.weixinBindOpenId = queryParams.weixinBindOpenId || ''
    this.$watch('params', () => {
      this.step1ValidateOk = this.validateStep1()
      this.step2ValidateOk = this.validateStep2()
    }, {deep: true})
  },
  methods: {
    toggleHidePwd () {
      this.hidePwd = !this.hidePwd
    },
    checkStep1 () {
      if (!this.step1ValidateOk) {
        return
      }
      api.register.checkStep1({
        inviteCode: this.params.inviteCode,
        phone: this.params.phone
      }).done((rs) => {
        let data = rs.data
        if (!data.invitationCodeValid) {
          modal.toast({
            message: '邀请码不存在，请重新输入',
            duration: 0.8
          })
          return
        }
        if (!data.phoneValid) {
          modal.toast({
            message: '手机号已经被注册，如已注册，请直接登录',
            duration: 0.8
          })
          return
        }
        this.step = 2
        this.leftItemText = '上一步'
        this.sendMsg()
      })
    },
    validateStep1 () {
      if (!this.params.phone || this.params.phone.length !== 11) {
        return false
      }
      if (!this.params.inviteCode || this.params.inviteCode.length <= 6) {
        return false
      }
      return true
    },
    back () {
      navigator.pop({
        animated: false
      })
    },
    validateStep2 () {
      if (!this.params.verifyCode || this.params.verifyCode.length !== 6) {
        return false
      }
      if (!this.params.password || this.params.password.length < 6) {
        return false
      }
      return true
    },
    showXy () {
      navigator.push('webpage.js?code=AGREEMENT')
    },
    register () {
      if (!this.step1ValidateOk || !this.step2ValidateOk || this.registerDoing) {
        return
      }
      // modal.alert({message: JSON.stringify(this.params)})
      this.registerDoing = true
      api.register.register(this.params).done(rs => {
        if (rs.data.success) {
          this.registered = true
          this.step = 3
          this.leftItemText = null
          if (this.param.weixinBindOpenId) {
            this.weixinBound = true
          }
        } else {
          modal.alert({message: rs.data.errMsg}, () => {

          })
        }
      }).always(rs => {
        this.registerDoing = false
      })
    },
    sendMsg () {
      if (this.cooldown > 0) {
        return
      }
      if (!this.params.phone || this.params.phone.length !== 11) {
        modal.alert({message: '请先输入正确的手机号'})
        return false
      }
      api.sms.register({
        phone: this.params.phone
      }).done(rs => {
        let data = rs.data
        if (data.success) {
          this.cooldown = data.cooldown
          this.cooldownCount()
        } else {
          if (data.cooldown) {
            this.cooldown = data.cooldown
            this.cooldownCount()
          } else {
            modal.alert({message: '短信验证码发送失败'})
          }
        }
      })
    },
    navbarLeftItemClick () {
      this.step = 1
      this.leftItemText = null
    },
    cooldownCount () {
      setTimeout(() => {
        this.cooldown--
        if (this.cooldown > 0) {
          this.cooldownCount()
        }
      }, 1000)
    },
    viewappear () {
      clipboard.getString(rs => {
        let data = rs.data
        if (data) {
          data = data.replace(/\n/g, '')
          let list = data.match(/•\d+•/g)
          if (list !== null && list.length > 0) {
            this.params.inviteCode = list[0].replace(/•/g, '')
          }
        }
      })
    }
  }
}
</script>
<style lang="scss">
  @import "./sass/var";
  @import "./sass/mixin";
  @import "./sass/icon";
  @import "./sass/buttons";
  @import "./sass/activeable";
  @import "./sass/form";
  @import "./sass/utilities";

  .container {
    background-color: #FFFFFF;
  }

  .agreement {
    flex-direction: row;
    &-txt {
      font-size: 28px;
      color: $color-muted;
      &-link {
        color: $color-warning;
      }
    }
  }

  .footerbar {
    position: fixed;
    bottom: 0;
    right: 0;
    left: 0;
    padding: 50px 0;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    &-icon {
      font-size: 110px;
      &-weixin {
        color: #77bb46;
      }
    }
  }

  .form-row-text {
    margin-top: 30px;
    align-items: center;
    justify-content: space-between;
    flex-direction: row;
    padding: 0 15px;
  }

  .sms-switch-btn {
    color: $color-info;
    font-size: 32px;
  }

  .register-new-btn {
    color: $color-warning;
    font-size: 32px;
  }

  .logo {
    width: 154px;
    height: 154px;
    border-radius: 154px;
    &-wrapper {
      justify-content: center;
      align-items: center;
      height: 180px;
    }
  }
  .register-success {
    background-color: #eee;
    &-top {
      align-items: center;
      justify-content: center;
      background-color: #ffffff;
      padding-top: 100px;
      padding-bottom: 100px;
      margin-bottom: 50px;
    }
  }
  .success-pic {
    width: 130px;
    height: 130px;
    margin-bottom: 20px;
  }
  .success-text {
    font-size: 28px;
    color: $color;
  }

  .login-form {
    padding: 0 40px;
    margin-top: 60px;
    overflow: hidden;
  }

  .login-wrap {

  }

  .login-btn {
    flex: 1;
  }

  .panel {
    transform: translateX(750px);
    position: fixed;
    top: 130px;
    left: 0;
    bottom: 0;
    right: 0;
    /*background-color: #ffffff;*/
  }
  .panel-show {
    transform: translateX(0);
  }
</style>
